/**
 * Created by msi on 2017/12/25 0025.
 */
import '../style/odui.less';
import Flox from './Flox';
var d3 = require("d3")
var MatrixGraphic = function () {
    var my = {}
    //数据格式为

    //[['Arsenal','Aston Villa',6]]

    var a = d3.rgb(255, 255, 255);  //浅蓝色
    var b = d3.rgb(145, 201, 94);    //蓝色
    var computeColor = d3.interpolate(a, b);

    var cellHeight = 10
    var x = null, y = null

    var max = Number.MIN_VALUE;
    var min = Number.MAX_VALUE;
//定义一个线性比例尺，将最小值和最大值之间的值映射到[0, 1]
    var linear = null;
    var orders = null;
    var data = null;
    var height = null;

    function drawMatrixGraphic(allFlows) {
        height = allFlows.length * cellHeight;
        y = d3.scale.ordinal().rangeBands([0, 24 * cellHeight])
        x = d3.scale.ordinal().rangeBands([0, height]) //离散的映射  x就已经算好了区间格网的大小了
        getAllData(function (flowData) {

            if (document.getElementById("matrixGraphic"))
                document.getElementById("matrixGraphic").innerHTML = "";
            data = allFlows.map(function (flow) {
                // max = max < flow.getValue() ? flow.getValue() : max;
                // min = min > flow.getValue() ? flow.getValue() : min;

                var oid = flow.getStartPt().id
                var did = flow.getEndPt().id
                var oName = flow.getStartPt().name
                var dName = flow.getEndPt().name
                var distance = Math.sqrt(Math.pow((flow.getStartPt().x - flow.getEndPt().x), 2) + Math.pow((flow.getStartPt().y - flow.getEndPt().y), 2))
                var pathName = oName + "->" + dName;

                var flow = flowData.filter(function (f) {
                    return f.o == oid && f.d == did
                })
                return {
                    "pathName": pathName,
                    "distance": distance,
                    "v": flow[0].v
                };
            });

            max = d3.max(data, function (d) {
                return d3.max(d.v.slice(0, 24))
            })
            min = d3.min(data, function (d) {
                return d3.min(d.v.slice(0, 24))
            })
            //可以画图例了
            drawLegend();
            linear = d3.scale.linear()
                .domain([min, max])
                .range([0, 1]);
            // 初始化排序方式
            orders = {
                //按名字排序
                ODDistance: d3.range(data.length).sort(function (a, b) {
                    return d3.ascending(data[a].distance, data[b].distance);
                }),
                ODValue: d3.range(data.length).sort(function (a, b) {
                    return d3.ascending(data[a].v[24], data[b].v[24]);
                }),
            };

            if (Flox.sort == "ODDistance") {
                x.domain(orders.ODDistance);
            } else {
                x.domain(orders.ODValue);
            }

            //转换成矩阵
            var matrix = []
            // 初始化矩阵值
            data.forEach(function (temRow, i) {
                matrix[i] = d3.range(24).map(function (j) {
                    return {x: i, y: j, z: temRow.v[j]};
                });
            });

            var svg = d3.select("#matrixGraphic").append("svg").attr("height", height + 10).attr("width", "100%");
            // //绘制画布
            // svg.append("rect")
            //     .attr("class", "background")
            //     .attr("width", "100%")
            //     .attr("height", height);

            var row = svg.selectAll(".row")
                .data(matrix)
                .enter().append("g")
                .attr("class", "row")
                .attr("transform", function (d, i) {
                    return "translate(120," + ((x(i)) + 10) + ")";
                })
                .each(function (row) {
                    var cell = d3.select(this).selectAll(".cell")
                        .data(row.filter(function (d) {
                            return d.z;
                        }))
                        .enter().append("rect")
                        .attr("class", "cell")
                        .attr("x", function (d) {
                            return (d.y * 10);
                        })
                        .attr("width", x.rangeBand())
                        .attr("height", x.rangeBand())
                        .style("fill", function (d) {
                            var t = linear(d.z);
                            var color = computeColor(t);
                            return color.toString();
                        })
                        .on("mouseover", mouseover)
                        .on("mouseout", mouseout).on("click", function (p) {
                        });

                });

            row.append("line")
                .attr("x2", height);//画一条0到width的直线


            //放文字
            row.append("text")
                .attr("x", -10)
                .attr("y", x.rangeBand() / 2)
                .attr("dy", ".18em")
                .attr("text-anchor", "end")
                .text(function (d, i) {
                    return data[i].pathName;
                });

        });
    }


    function reSort(type) {
        if (document.getElementById("matrixGraphic"))
            document.getElementById("matrixGraphic").innerHTML = "";
        switch (type) {
            case "ODValue":
                x.domain(orders.ODValue);
                break
            case "ODDistance":
                x.domain(orders.ODDistance);
                break
        }

        //转换成矩阵
        var matrix = []
        // 初始化矩阵值
        data.forEach(function (temRow, i) {
            matrix[i] = d3.range(24).map(function (j) {
                return {x: i, y: j, z: temRow.v[j]};
            });
        });
        var svg = d3.select("#matrixGraphic").append("svg").attr("height", height + 10).attr("width", "100%");
        // //绘制画布
        // svg.append("rect")
        //     .attr("class", "background")
        //     .attr("width", "100%")
        //     .attr("height", height);

        var row = svg.selectAll(".row")
            .data(matrix)
            .enter().append("g")
            .attr("class", "row")
            .attr("transform", function (d, i) {
                return "translate(120," + ((x(i)) + 10) + ")";
            })
            .each(function (row) {
                var cell = d3.select(this).selectAll(".cell")
                    .data(row.filter(function (d) {
                        return d.z;
                    }))
                    .enter().append("rect")
                    .attr("class", "cell")
                    .attr("x", function (d) {
                        return (d.y * 10);
                    })
                    .attr("width", x.rangeBand())
                    .attr("height", x.rangeBand())
                    .style("fill", function (d) {
                        var t = linear(d.z);
                        var color = computeColor(t);
                        return color.toString();
                    })
                    .on("mouseover", mouseover)
                    .on("mouseout", mouseout).on("click", function (p) {
                    });

            });

        row.append("line")
            .attr("x2", height);//画一条0到width的直线


        //放文字
        row.append("text")
            .attr("x", -10)
            .attr("y", x.rangeBand() / 2)
            .attr("dy", ".18em")
            .attr("text-anchor", "end")
            .text(function (d, i) {
                return data[i].pathName;
            });
    }

    function mouseover(p) {
        //就画出当前OD量的曲线图
        d3.selectAll(".row text").classed("active", function (d, i) {
            return i == p.x;
        });
        d3.selectAll(".column text").classed("active", function (d, i) {
            return i == p.y;
        });
    }

    function mouseout() {
        d3.selectAll("text").classed("active", false);
    }

//绘制图例
    function drawLegend() {
        if (document.getElementById("matrixGraphicegend")) {
            document.getElementById("matrixGraphicegend").innerHTML = "";
        } else {
            return;
        }
        var width = 400;
        var svg = d3.select("#matrixGraphicegend").append("svg")
            .attr("width", width)
            .attr("height", 40)
            .append("g");

        //定义一个线性渐变
        var defs = svg.append("defs");

        var linearGradient = defs.append("linearGradient")
            .attr("id", "linearColor")
            .attr("x1", "0%")
            .attr("y1", "0%")
            .attr("x2", "100%")
            .attr("y2", "0%");

        var stop1 = linearGradient.append("stop")
            .attr("offset", "0%")
            .style("stop-color", a.toString());

        var stop2 = linearGradient.append("stop")
            .attr("offset", "100%")
            .style("stop-color", b.toString());

        //添加一个矩形，并应用线性渐变

        var colorRect = svg.append("rect")
            .attr("x", 15)
            .attr("y", 0)
            .attr("width", 200)
            .attr("height", 30)
            .style("fill", "url(#" + linearGradient.attr("id") + ")");

//添加文字
        var minValueText = svg.append("text")
            .attr("class", "valueText")
            .attr("x", 5)
            .attr("y", 30)
            .attr("dy", "-0.5em")
            .text(function () {
                return min;
            });

        var maxValueText = svg.append("text")
            .attr("class", "valueText")
            .attr("x", 215)
            .attr("y", 30)
            .attr("dy", "-0.5em")
            .text(function () {
                return max;
            });

    }


    function getAllData(callback) {
        var flowPath = "FlowData.json";
        d3.json(flowPath, function (flowDatas) {
            var flowData = flowDatas.links
            callback(flowData)
        });
    }

    my.drawMatrixGraphic = function (allFlows) {
        drawMatrixGraphic(allFlows);
    };
    my.reSort = function (type) {
        reSort(type);
    }

    return my
};
export default MatrixGraphic;